import { reactive } from 'vue'
import { useHttpRequest } from '@/api/chunfeng/apiRequest'
import { DeliveryOrderData, QueryDeliveryOrderParam } from '@/api/chunfeng/wms/delivery/interfaces'
import { useDeliveryOrderApi } from '@/api/chunfeng/wms/delivery'
import { Form } from 'ant-design-vue'

const { executeQueryRequest, executeCommandRequest } = useHttpRequest()

export const useDeliveryOrderListFunctions = () => {
  const queryParam = reactive<QueryDeliveryOrderParam>({
    warehouseId: '',
    customerId: undefined,
    sourceId: undefined,
    status: undefined,
    occurredStart: undefined,
    occurredEnd: undefined,
  })
  const resultDataSet = reactive<Array<DeliveryOrderData>>([])
  const { queryDeliveryOrder, finishDeliveryOrder } = useDeliveryOrderApi()

  const columns = [
    {
      title: '仓库名称',
      dataIndex: 'warehouseName',
      key: 'warehouseName',
    },
    {
      title: '客户',
      dataIndex: 'customerName',
      key: 'customerName',
    },
    {
      title: '发生日期',
      dataIndex: 'occurredAt',
      key: 'occurredAt',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      slots: { customRender: 'status' },
    },
    {
      title: '操作',
      key: 'action',
      slots: { customRender: 'action' },
    },
  ]

  const rules = reactive({
    warehouseId: [
      {
        required: true,
        message: '请选择仓库',
      },
    ],
    customerId: [
      {
        required: false,
      },
    ],
    sourceId: [
      {
        required: false,
      },
    ],
    occurredStart: [
      {
        required: false,
      },
    ],
    occurredEnd: [
      {
        required: false,
      },
    ],
  })

  const { resetFields, validateInfos, validate } = Form.useForm(queryParam, rules)

  function edit(uid: string) {}

  function reset() {
    resetFields()
  }

  function query() {
    resultDataSet.length = 0
    validate().then(() => {
      executeQueryRequest(queryDeliveryOrder(queryParam), (results: DeliveryOrderData[]) => {
        resultDataSet.push(...results)
      })
    })
  }

  function customerSelected(customerId: string) {
    queryParam.customerId = customerId
  }

  function warehouseSelected(warehouseId: string) {
    queryParam.warehouseId = warehouseId
  }

  function finish(uid: string) {}

  return {
    queryParam,
    resultDataSet,
    columns,
    query,
    reset,
    edit,
    finish,
    validateInfos,
    customerSelected,
    warehouseSelected,
  }
}
